//
//  HSClassTableController.swift
//  HomeSchoolDemo
//
//  Created by rimi on 16/9/30.
//  Copyright © 2016年 赖虹宇. All rights reserved.
//

import UIKit

class HSClassTableController: UIViewController {
     //标签宽度
    let labelW:CGFloat = screenW/8
    let labelH:CGFloat = 44
    //全局的集合视图属性
    var collectionView : UICollectionView!
    //数据源数组
    var dataArray : [HSClassTableModel] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        //顶部导航条
        setupTopUI()
        //集合视图
        addCollectionView()
        //周视图
        setupWeekView()
        //左边视图和线条视图
        setupLeftClassTimeView()
        //请求课表数据
        loadData()
    }
    //请求课表数据
    func loadData(){
        //接口地址
        let url = "ZH-schoolname-S-curriculum"
        //参数
        let key  = userInfo["key"] as! String
        let param = ["key":key]
        //请求数据
        HSNetwordTools.shared.downloadData(urlStr: url, parameters: param) {[weak self] (data, error) in
            //判断网络是否异常
            guard  let data = data as? NSDictionary else{
                //弹窗提示 网络异常-在没有网络的情况下
                return
            }
            //判断返回的数据是否正常，
            switch data["result"] as! Int {
            case 0 :
                print("数据获取正常")
                //获得数据数组
                let dataArr = data["data"] as! NSArray
                print(dataArr)
                for dict in dataArr{
                    //先转成字典类型
                    let cDict = dict as? NSDictionary
                    //先获得字典的keys,并按照小--大排序
                    
                    let keys = (cDict?.allKeys as! [String]).sorted{
                    $0 < $1
                    }
                    //循环获得每一天的课程的字典
                    for k in keys {
                        //获得字典
                        let d = cDict?[k] as! [String:Any]
                        //字典转模型
                        let model = HSClassTableModel(dict: d)
                        //添加到数据源数组中
                       self?.dataArray.append(model)
                        //添加空白对象  --每次到第五个的时候,因为第五个的时候有午休视图遮挡
                        if k == "c4" {
                            self?.dataArray.append(HSClassTableModel(dict: [:]))
                        }
                    }
                }
                //到这里就表示所有数据全部处理完成
                //刷新视图
                self?.collectionView.reloadData()
            case 1 :
                print("参数错误")
            default:
                break
            }
            
        }
    }
}

// MARK: - 设置UI
extension HSClassTableController{
    //设置顶部UI
    func setupTopUI(){
        //        模拟一个假导航栏
        let navVc = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 64))
        navVc.backgroundColor = UIColor().colorWithHex(0x009ee7)
        view.addSubview(navVc)
        //        返回按钮
        let backBtn = UIButton(type: .system)
        backBtn.frame = CGRect(x: 8, y: 16, width: 70, height: 48)
        backBtn.setImage(UIImage(named:"back"), for: .normal)
        backBtn.addTarget(self, action: #selector(backBtnClicked), for: .touchUpInside)
        navVc.addSubview(backBtn)
        //        文字
        let label = UILabel(frame: CGRect(x: 78, y: 16, width: 150, height: 48))
        label.text = "课表"
        label.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        label.font = UIFont.systemFont(ofSize: 20)
        
        navVc.addSubview(label)
        
        view.addSubview(navVc)
    }
    //设置周视图
    func setupWeekView(){
        //创建周数组
        let weekTitle = [" ","一","二","三","四","五","六","日"] as NSArray
        //循环添加视图
        weekTitle.enumerateObjects ({ (title, i, _) in
            //初始化
            let label = UILabel(frame: CGRect(x: labelW * CGFloat(i), y: 64, width: labelW, height: labelH))
            label.text = title as? String
            label.textColor = UIColor().colorWithHex(0x009ee7)
            label.textAlignment = .center
            label.textColor = UIColor().colorWithHex(0x00a0e9)
            label.font = UIFont.systemFont(ofSize: 13)
            view.addSubview(label)
            
        })
    }
    //设置课时视图
    func setupLeftClassTimeView() {
        //循环
        for i in 1..<10 {
            if i == 5 {
                let btn = UIButton(type: .custom)
                btn.frame = CGRect(x: 0, y: 65+labelH*CGFloat(i), width: screenW, height: labelH-1)
                btn.setBackgroundImage(UIImage(named:"curriculum_wuxiu_bg"), for: .normal)
                btn.setTitle("午休", for: .normal)
                btn.isUserInteractionEnabled = false
                btn.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
                view.addSubview(btn)
            }else{
                
                let label = UILabel(frame: CGRect(x: 0, y: labelH*CGFloat(i)+64, width: labelW, height: labelH))
                label.textColor = UIColor().colorWithHex(0x009ee7)
                if i > 5 {
                    label.text = "\(i-1)"
                }else{
                    label.text = "\(i)"
                }
                label.textAlignment = .center
                label.textColor = UIColor().colorWithHex(0x00a0e9)
                label.font = UIFont.systemFont(ofSize: 13)
                view.addSubview(label)
            }
            //添加文字的时候同时添加线条
            let lineV = UIView(frame: CGRect(x: 8, y: 64+labelH*CGFloat(i+1), width: UIScreen.main.bounds.width-16, height: 1))
            lineV.backgroundColor = UIColor().colorWithHex(0x00a0e9)
            view.addSubview(lineV)
            
            
        }
    }
    //中间集合视图
    func addCollectionView(){
        //设置布局对象
        let flowLayout = UICollectionViewFlowLayout()
        //设置大小和间距
        flowLayout.itemSize = CGSize(width: labelW, height: labelH)
        flowLayout.minimumLineSpacing = 0   //最小水平距离
        flowLayout.minimumInteritemSpacing = 0  //最小垂直距离
        //设置滚动方向  --在这里设置为左右滚动
        flowLayout.scrollDirection = .horizontal
        
        let rect = CGRect(x: labelW, y: labelH+64, width: labelW*CGFloat(7), height: labelH*CGFloat(9) )
        collectionView = UICollectionView(frame: rect, collectionViewLayout:flowLayout )
        collectionView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        //设置代理和数据源 ---这里的课表不需要点击 所以只设置数据源代理
        collectionView.dataSource = self
        //注册原形cell
        collectionView.register(HSClassTableCell.self, forCellWithReuseIdentifier: "classTableCell")
        
        view.addSubview(collectionView)
        
    }
    
    //返回按钮监听方法
    func backBtnClicked(){
        
        dismiss(animated: true, completion: nil)
    }
    
}

// MARK: - 集合视图的数据源方法
extension HSClassTableController:UICollectionViewDataSource{
    //格子数量
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }
    //格子视图
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        //缓存获取
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "classTableCell", for: indexPath) as? HSClassTableCell
        cell?.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        
        //赋值
        cell?.titleL?.text = dataArray[indexPath.item].courseName
        
        return cell!
}
}
